const superagent = require('superagent');
const { geojsonData, formatGaodeParam, Ue4Data } = require('./function/mockGps');
const { GAODE_KEY, JDBC } = require('./config');
const { getDetailAddress, getJurisdiction } = require('./function/common');

//数据库信息
const { START_INDEX, TABLE_NAME, TABLE_KEYS, TABLE_VALUES } = require('./dbscript/access_geo');
// const { START_INDEX, TABLE_NAME, TABLE_KEYS, TABLE_VALUES } = require('./dbscript/activity_geo');
// const { START_INDEX, TABLE_NAME, TABLE_KEYS, TABLE_VALUES } = require('./dbscript/camera_geo');
// const { START_INDEX, TABLE_NAME, TABLE_KEYS, TABLE_VALUES } = require('./dbscript/police_box_geo');
// const { START_INDEX, TABLE_NAME, TABLE_KEYS, TABLE_VALUES } = require('./dbscript/police_car_geo');
// const { START_INDEX, TABLE_NAME, TABLE_KEYS, TABLE_VALUES } = require('./dbscript/police_geo');


start();
async function start(){
    console.log('开始运行...');
    let superagentResult = [];
    console.log('正在请求数据中...');
    for(let i=0;i<formatGaodeParam.length;i++) {
        console.log(`正在进行第${i+1}次请求...`);
        let result = await superagent.get(`https://restapi.amap.com/v3/geocode/regeo?output=json&location=${formatGaodeParam[i]}&key=${GAODE_KEY}&radius=1000&extensions=all&batch=true`).catch((e) => { console.log('获取信息', e); });
        if (!result || !result.text) console.log(`第${i}条高德res为空`);
        let {info, regeocodes:data} = JSON.parse(result.text);
        if (info !== 'OK') {
            console.log('请求数据失败...');
            return;
        }
        superagentResult = superagentResult.concat(data);
    }
    console.log(`请求完成，开始拼装数据...`);
    // console.log(superagentResult, 'superagentResult---')
    let sqlObj = superagentResult.map((item, index) => {
        return {
            'INDEX_id': index + START_INDEX, //索引从1开始
            'adcode': item.addressComponent.adcode,
            'province': item.addressComponent.province,
            'city': item.addressComponent.city,
            'district': item.addressComponent.district,
            'town_ship': item.addressComponent.township,
            'jurisdiction': getJurisdiction(item.addressComponent.township),
            'detail_address': getDetailAddress(item.formatted_address, item.addressComponent.province, item.addressComponent.city, item.addressComponent.district, item.addressComponent.township),
            'lng_x': geojsonData[index][0],
            'lat_y': geojsonData[index][1],
            'internal_coordinate_x': Ue4Data[index][0],
            'internal_coordinate_y': Ue4Data[index][1],
            'format_address': item.formatted_address
        }
    })
    console.log(`拼装数据完成，准备连接数据库写入数据...`);

    // console.log(sqlObj, 'sqlObj-------')

    //数据库配置
    let pg = require('pg');
    let client = new pg.Client(JDBC);
    client.connect(async function(err, client, done){
        if (err) {
            console.log('连接postgresql出错');
        } else {
            console.log('连接postgresql成功');

            for(let i=0;i<sqlObj.length;i++) {
                let { 
                    INDEX_id,
                    adcode, 
                    province, 
                    city, 
                    district, 
                    town_ship, 
                    jurisdiction, 
                    detail_address, 
                    lng_x,
                    lat_y,
                    internal_coordinate_x,
                    internal_coordinate_y,
                    format_address
                } = sqlObj[i];
                
                await client.query(`insert into ${TABLE_NAME} (${TABLE_KEYS}) values ( ${TABLE_VALUES} )`, [ 
                    INDEX_id, 
                    adcode, 
                    province, 
                    city, 
                    district, 
                    town_ship, 
                    jurisdiction, 
                    detail_address, 
                    lng_x,
                    lat_y,
                    internal_coordinate_x,
                    internal_coordinate_y,
                    format_address
                    ]
                );
                console.log(`插入第${i+1}条数据成功！`)
            }

        }

        console.log('完成！')
    });
}


